import { login, rbacPermissionGetMyPermission } from '@/api/login'
import Layout from '@/layout'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { emptyCacheAction } from '@/api/common'

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve) //import加载里面路径不能用变量。require可以（node解析）@/ 需要拿出来，如果不拿出来，就无法解析正确
}


function filterAsyncRoutes(routes) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if(tmp.component === 'Layout') {
      tmp.component = Layout
    }else{
      tmp.component = loadView(tmp.component)
    }
    if (tmp.menu.length) {
      tmp.children = filterAsyncRoutes(tmp.menu)
    }
    const copy_tmp = {
      path: tmp.path,
      component: tmp.component,
      meta: {
        title: tmp.name,
        icon: tmp.icon
      },
      children: tmp.children? tmp.children : []
    }
    res.push(copy_tmp)
  })
  return res
}

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    rolesList: [],
    company_id: '',
    btnPermission: [],
    menuPermission: [],
    userId: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROLESLIST: (state, rolesList) => {
    state.rolesList = rolesList
  },
  SET_COMPANY: (state, payload) => {
    state.company_id = payload
  },
  SET_PERMISSION: (state, payload) => {
    state.btnPermission = payload.btnPermission
    state.menuPermission = payload.menuPermission
  },
  SET_USER_ID: (state, payload) => {
    state.userId = payload
  }
}

const actions = {
  // user login
  login({ commit, dispatch }, userInfo) {
    const { phone, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ phone,password }).then(response => {
        localStorage.setItem('userInfo', JSON.stringify(response.data))
        const { name, id, token } = response.data
        commit('SET_TOKEN', token)
        commit('SET_NAME', name)
        commit('SET_COMPANY', id)

        dispatch('tagsView/delAllViews', {}, { root: true })
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      rbacPermissionGetMyPermission().then(res => {
        let menuPermission = []
        menuPermission = filterAsyncRoutes(res.data)
        commit('SET_PERMISSION', { btnPermission: [], menuPermission })
        const roles = ['admin']
        commit('SET_ROLESLIST', menuPermission)
        commit('SET_ROLES', roles)

        resolve({ roles, menuPermission })
      })
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      emptyCacheAction()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

